﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Common;
using System.Collections.Generic;
using Xhelper.ApiGate;
using Models;
using System.Security.Claims;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using System.Linq;
using LiteDB;
using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet;
using System.Xml.Linq;

namespace Web.Controllers
{
  public class BookMarks
  {
    public BookMarks() { _id = ObjectId.NewObjectId().ToString(); }
    [BsonId]
    public string _id { get; set; }
    public string ver { get; set; }
    public String item { get; set; }
  }

  /// <summary>
  /// chrome 收藏夹管理
  /// </summary>
  [Route("api/[controller]")]
  public class BookMarkManageController : BaseController
  {
    private MqttClientService _mqttClientService;

    public BookMarkManageController(MqttClientService mqttClientService)
    {
      _mqttClientService = mqttClientService;
    }

    /// <summary>
    /// 拉取收藏夹
    /// </summary>
    /// <returns></returns>
    [HttpGet("[action]")]
    public async Task<IActionResult> PullBookMark(string ver = "")
    {      
      var res = JsonFileHelper.GetObs("bookmark");
      if (String.IsNullOrWhiteSpace(res))
      {
        return await PublicTool.ReturnSuccess(new { ver = "", msg = "云端暂无备份内容" });
      }
      else
      {
        return await PublicTool.ReturnSuccess(JsonConvert.DeserializeObject<Dictionary<String,string>>(res));
      }
    }

    /// <summary>
    /// 推送收藏夹（只保留最新版本）
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> PushBookMark([FromBody] Dictionary<string, string> model)
    {
      var _ver = PublicTool.NowTS;
      var res = JsonFileHelper.UpdateObs("bookmark", JsonConvert.SerializeObject(new { ver = _ver, bookmark = model["bookmark"] }));
      return await PublicTool.ReturnSuccess(new { ver = _ver });
    }


    [HttpGet("[action]")]
    public async Task<IActionResult> PullNote(string id = "")
    {
      var res = JsonFileHelper.GetItem(id);
      return await PublicTool.ReturnSuccess(res);
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> GetAccounts()
    {
      return await PublicTool.ReturnSuccess(JsonFileHelper.GetAccountList());
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> SiriTodo(string what)
    {
      var data = new Dictionary<string, string> { ["Content"] = what };
      _mqttClientService.Publish("siri/action/a", what);
      return await PublicTool.ReturnSuccess(new { action = "siri", what = what });
    }

    [HttpPost("[action]")]
    public async Task<IActionResult> PushNote([FromBody] Dictionary<string, string> model)
    {
      var res = JsonFileHelper.Update(model["id"], model["content"]);
      return res ? await PublicTool.ReturnSuccess("保存成功！") : await PublicTool.ReturnError("推送失败！");
    }

    [HttpPost("[action]")]
    public async Task<IActionResult> PushObs([FromBody] Dictionary<string, string> model)
    {
      var res = JsonFileHelper.UpdateObs(model["name"], model["content"]);
      return res ? await PublicTool.ReturnSuccess("保存成功！") : await PublicTool.ReturnError("推送失败！");
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> PullObs(string name = "test")
    {
      var res = JsonFileHelper.GetObs(name);
      return await PublicTool.ReturnSuccess(res);
    }

    // 保存多个版本副本，
    //[HttpPost("[action]")]
    //public async Task<IActionResult> PushBookMarkB([FromBody] Dictionary<string, string> model)
    //{
    //  String item = model["bookmark"];
    //  try
    //  {
    //    #region 获取最后提交的版本，并对比当前推送的内容，内容相同则回复请求
    //    var items = LiteDbHelper.GetItems<BookMarks>("Record", "bookmark.db");
    //    var lastVer = items.Max("ver");
    //    var bookmarkOfLastVer = items.FindOne((x) => x.ver == lastVer);
    //    if (bookmarkOfLastVer.item == model["bookmark"]) return await PublicTool.ReturnSuccess($"已经是最新副本:{lastVer}");
    //    #endregion

    //    #region 保存新版本内容
    //    List<BookMarks> bmLis = new List<BookMarks>();
    //    var _ver = PublicTool.NowTS;
    //    bmLis.Add(new BookMarks { ver = _ver, item = model["bookmark"] });
    //    LiteDbHelper.InsertBulk<BookMarks>("Record", bmLis, "bookmark.db");
    //    return await PublicTool.ReturnSuccess("收藏夹已备份到云端！");
    //    #endregion
    //  }
    //  catch (Exception e)
    //  {
    //    return await PublicTool.ReturnError(e.Message);
    //  }
    //}
  }
}
